﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExamAnalysis.Core.Statistics
{
    public static class Method
    {
        public static double CalculateMAD(List<double> numbers)
        {
            double avg = numbers.Average();
            double result = 0;
            foreach (double number in numbers)
            {
                result += Math.Abs(number - avg);
            }
            double n = numbers.Count();
            result = result / n;
            return result;
        }

        public static int CalculatePeriodCount(double min, double max, List<double> numbers)
        {
            int result = 0;
            foreach (double number in numbers)
            {
                if (number >= min && number <= max)
                {
                    result++;
                }
            }
            return result;
        }
        /// <summary>
        /// 计算分数在分数组中的排名
        /// </summary>
        /// <param name="score"></param>
        /// <param name="scores"></param>
        /// <returns></returns>
        public static int CalculateRankCount(decimal score, List<decimal> scores)
        {
            int result = 1;
            foreach (decimal current in scores)
            {
                if (score < current)
                {
                    result++;
                }
            }
            return result;
        }
        /// <summary>
        /// 区分度D=PH－PL，PH为高分组（即得分最高的27%）被试在该题上的通过率，PL为低分组（即得分最低的27%）被试在该题上的通过率
        /// </summary>
        /// <param name="percent"></param>
        /// <param name="scores"></param>
        /// <returns></returns>
        public static decimal CalCulateDifferenceDegree(decimal percent, decimal totalScore, List<decimal> scores)
        {
            int count = scores.Count();
            List<decimal> highScores = new List<decimal>();
            List<decimal> lowScores = new List<decimal>();
            int high = Convert.ToInt32(Math.Round(count * percent));
            int low = count - high;
            foreach (decimal score in scores)
            {
                int rank=CalculateRankCount(score, scores);
                if ( rank< high)
                {
                    highScores.Add(score);
                }
                else if (rank > low)
                {
                    lowScores.Add(score);
                }
            }
            if (highScores.Count() == 0) highScores.Add(scores.Max());
            if (lowScores.Count() == 0) lowScores.Add(scores.Min());
            //这个算法因为排名问题，有点bug
            return (highScores.Average() - lowScores.Average()) * 100 / totalScore;
        }

        public static double CalMedian(IEnumerable<double?> scores)
        {
            return MathNet.Numerics.Statistics.Statistics.Median(scores);
        }
    }
}
